/**
 * 
 */
package org.statewalker.parser.xhtml.cleaner;

import org.statewalker.parser.base.Parser;
import org.statewalker.parser.xhtml.parser.XhtmlParserFactory;
import org.statewalker.parser.xhtml.serializer.XhtmlListener;
import org.statewalker.parser.xhtml.serializer.XmlPrinter;
import org.statewalker.parser.xhtml.validator.XHTMLValidatorFactory;
import org.statewalker.tokenizer.CharStream;
import org.statewalker.tokenizer.StreamToken;

public class HtmlToXhtmlConverter {

    public interface IWriter {

        void print(String str);

    }

    public class StringWriter implements IWriter {

        private StringBuilder fBuilder = new StringBuilder();

        public void clean() {
            fBuilder.delete(0, fBuilder.length());
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (!(obj instanceof StringWriter))
                return false;
            StringWriter o = (StringWriter) obj;
            return fBuilder.equals(o.fBuilder);
        }

        @Override
        public int hashCode() {
            return fBuilder.hashCode();
        }

        public void print(String str) {
            fBuilder.append(str);
        }

        @Override
        public String toString() {
            return fBuilder.toString();
        }

    }

    private XhtmlParserFactory fParserFactory;

    public HtmlToXhtmlConverter(XHTMLValidatorFactory factory) {
        fParserFactory = new XhtmlParserFactory(factory);
    }

    public void cleanup(CharStream stream, final IWriter writer) {
        XHTMLValidatorFactory factory = fParserFactory.getValidatorFactory();
        XmlPrinter printer = new XmlPrinter() {
            @Override
            protected void print(String str) {
                writer.print(str);
            }
        };
        XhtmlListener listener = new XhtmlListener(factory, printer);
        Parser parser = fParserFactory.newParser(stream, listener);
        while (true) {
            StreamToken token = parser.loadNext();
            if (token == null)
                break;
        }
        parser.close();
    }

    public String cleanup(String str) {
        StringWriter writer = new StringWriter();
        CharStream reader = new CharStream(str);
        cleanup(reader, writer);
        return writer.toString();
    }

}